package com.wuyou.mid;

import java.util.Arrays;

/**
 * 8. 字符串转换整数 (atoi)
 */
public class MyAtoi {

    public static void main(String[] args) {
        String s = "18446744073709551617";
        int x = 20;
        System.out.println(solution_1(s));
    }

    public static int solution_1(String s) {
        char[] chars = s.toCharArray();
        int i = 0;
        for (int j = 0; j < chars.length; j++) {
            if (chars[i] == ' ') i++;
            else break;
        }
        int index = i;
        if (i >= s.length()) return 0;
        if (chars[i] == '-' || chars[i] == '+') {
            i += 1;
        }
        Long res = 0L;
        while (i < chars.length && chars[i] >= '0' && chars[i] <= '9') {
            if (res * 10 < res) {
                return chars[index] == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            res *= 10;
            res += chars[i] - 48;
            i++;
        }
        if (res - Integer.MAX_VALUE > 0) {
            return chars[index] == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        } else {
            return chars[index] == '-' ? res.intValue() * -1 : res.intValue();
        }
    }
}
